﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.StaticFiles;
using RayD.Core;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace RayD.Core
{
    /// <summary>
    /// 基于虚路径的文件操作
    /// </summary>
    public class IOHelper
    {
        static string _contentRoot = string.Empty;
        static IContentTypeProvider _contentTypeProvider;
        public IOHelper(string contentPath, IContentTypeProvider contentTypeProvider)
        {
            _contentRoot = contentPath;
            _contentTypeProvider = contentTypeProvider;
        }

        /// <summary>
        /// 读取文件
        /// </summary>
        /// <param name="VirtualPath">文件虚路径</param>
        /// <returns></returns>
        public static FileInfo Read(string VirtualPath)
        {
            //空路径直接返回
            if (VirtualPath.IsEmpty())
            {
                return null;
            }

            //文件绝对地址
            string FullPath = Path.Combine(_contentRoot, VirtualPath);
            //判断是否存在文件
            if (System.IO.File.Exists(FullPath))
            {
                FileInfo fileInfo = new FileInfo();
                #region 基本信息
                fileInfo.FileName = Path.GetFileName(FullPath); //文件原名
                fileInfo.FileExtension = Path.GetExtension(fileInfo.FileName);//文件后缀  
                string contentType;
                _contentTypeProvider.TryGetContentType(FullPath, out contentType);
                fileInfo.ContentType = contentType;//文件类型
                fileInfo.BasePath = _contentRoot;//文件根目录
                var stream = System.IO.File.OpenRead(FullPath);
                fileInfo.FileStream = stream;//文件流
                #endregion
                return fileInfo;
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 将待上传文件保存到硬盘
        /// </summary>
        /// <param name="UploadPath">文件上传路径（相对）</param>
        /// <returns></returns>
        public static FileInfo Save(string UploadPath)
        {
            var file = HttpContextHelper.Instance.Request.Form.Files.FirstOrDefault();//获取文件数据
            //没有文件上传，直接返回
            if (file.IsEmpty())
            {
                return null;
            }

            UserInfo userInfo = AuthenticationHelper.LoginUserInfo;//登录用户信息
            FileInfo fileInfo = new FileInfo();
            #region 基本信息
            fileInfo.FileName = file.FileName;//文件原名
            fileInfo.FileExtension = Path.GetExtension(file.FileName);//文件后缀  
            fileInfo.FileSize = file.Length.ToString();//文件大小
            string contentType;
            _contentTypeProvider.TryGetContentType(file.FileName, out contentType);
            fileInfo.ContentType = contentType;//文件类型
            fileInfo.BasePath = _contentRoot;//文件根目录
            #endregion

            #region 上传信息
            fileInfo.UploadPath = UploadPath;//文件上传路径
            fileInfo.UserId = userInfo.account ?? "unkown";//上传用户Id
            fileInfo.UploadDate = DateTime.Now.ToString("yyyyMMdd");//上传日期时间
            fileInfo.FileGuid = Guid.NewGuid().ToString();//文件新名 
            #endregion
            //创建文件夹
            string path = Path.GetDirectoryName(fileInfo.FullPath);
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            //保存文件
            using (FileStream fs = System.IO.File.Create(fileInfo.FullPath))
            {
                file.CopyTo(fs);
                fs.Flush();
            }
            fileInfo.FileStream = file.OpenReadStream();//文件流
            return fileInfo;
        }

        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="VirtualPath">虚路径</param>
        /// <returns></returns>
        public static bool Delete(string VirtualPath)
        {
            if (VirtualPath.IsEmpty())
            {
                return false;
            }

            //文件绝对地址
            string FullPath = Path.Combine(_contentRoot, VirtualPath);
            //删除文件
            if (System.IO.File.Exists(FullPath))
            {
                System.IO.File.Delete(FullPath);
            }
            return true;
        }
    }

    /// <summary>
    /// 文件信息
    /// </summary>
    public class FileInfo
    {
        #region 基本信息
        /// <summary>
        /// 文件原名
        /// </summary>
        public string FileName { get; set; }
        /// <summary>
        /// 文件原名（不包含后缀）
        /// </summary>
        public string FileNameWithoutExtension { get; set; }
        /// <summary>
        /// 文件后缀
        /// </summary>
        public string FileExtension { get; set; }
        /// <summary>
        /// 文件大小
        /// </summary>
        public string FileSize { get; set; }
        /// <summary>
        /// 文件类型
        /// </summary>
        public string ContentType { get; set; }
        /// <summary>
        /// 文件根目录
        /// </summary>
        public string BasePath { get; set; } 
        /// <summary>
        /// 文件流
        /// </summary>
        public Stream FileStream { get; set; }
        #endregion

        #region 上传信息
        /// <summary>
        /// 上传路径（相对）
        /// </summary>
        public string UploadPath { get; set; }
        /// <summary>
        /// 上传用户Id
        /// </summary>
        public string UserId { get; set; }
        /// <summary>
        /// 上传日期时间
        /// </summary>
        public string UploadDate { get; set; }
        /// <summary>
        /// 文件新名
        /// </summary>
        public string FileGuid { get; set; }
        /// <summary>
        /// 文件虚路径
        /// </summary>
        public string VirtualPath
        {
            get
            {
                return string.Format("{1}{0}{2}{0}{3}{0}{4}{5}", Path.DirectorySeparatorChar, this.UploadPath, this.UserId, this.UploadDate, this.FileGuid, this.FileExtension);
            }
        }
        /// <summary>
        /// 文件全路径（根目录 + 虚路径）
        /// </summary>
        public string FullPath
        {
            get
            {
                return string.Format("{1}{0}{2}{0}{3}{0}{4}{0}{5}{6}", Path.DirectorySeparatorChar, this.BasePath, this.UploadPath, this.UserId, this.UploadDate, this.FileGuid, this.FileExtension);
            }
        } 
        #endregion
    }
}
